<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader 
    @add='addFn' 
    :list='list'
     @checkChange='checkChangeFn'>
     </TodoHeader>

    <TodoMain 
    :list='showList'
     @del='delFn'
      @change='changeFn'>
      </TodoMain>

    <TodoFooter 
    :list='list'
    :type='type'
     @changeType='changeTypeFn'
     @clear='clearFn'
     >
   </TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css"
import "./styles/index.css"
    
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";


export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      
      list: JSON.parse(localStorage.getItem('todolist')) || [],//取本地数据 JSON.parse  ,要给个空数组否则本地取不到数据会报错
      type:'all'//定义全部为all 未完成no 已完成yes
      

    };
  },

  methods:{
    //1.删除操作完成
    delFn(id){
     this.list= this.list.filter(item=>item.id !==id)
    },
    //2.改变选中状态完成
    changeFn(id){
     const res= this.list.find(item=>item.id===id)//得到一个对象
     res.isDone=!res.isDone//取反
    },
    //3.header 添加
    addFn(task){
      this.list.push(
        {id:this.list.length ? this.list.at(-1).id+1 :100,
        name:task,
        isDone: false 
        }//list.at(-1)最后一项
      )

    },
    //4.header 全选
    checkChangeFn(val){
      //遍历所有
      this.list.forEach(item=>item.isDone=val)
    },
    //5.footer 改变type 把all yes no传过来 进行绑定
    changeTypeFn(type){
      this.type=type
    },
    //6.footer 清除已完成，删数据
    clearFn(){
     this.list= this.list.filter(item=>!item.isDone)
    }
  },

 //showList函数给到min组件即可，footer组件只是进行type的绑定
  computed:{
    showList(){
      //切记不要加this.list=  否则是在删数组
      if(this.type==='yes'){
        return this.list.filter(item=>item.isDone)//item.isDone=true
      }else if(this.type ==='no'){
        return this.list.filter(item=>!item.isDone)//item.isDone=false
      }else{
        return this.list
      }
    }
  },

//7.深度监听 存到本地 JSON.stringify
  watch:{
    list:{
      deep:true,
      handler(newVal){
        localStorage.setItem('todolist',JSON.stringify(newVal))
      }
    }
  }

};
</script>